import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
class EmailUtil():
    def __init__(self, HOST:str, PORT:int,from_addr:str,pwd:str):
        self.server = smtplib.SMTP_SSL(HOST, PORT)     
        self.server.login(from_addr, pwd)
        self.from_addr=from_addr

    def msg_text_attach(self,plain_text):
        """读取文件或者使用变量传递纯文本"""
        if os.path.isfile(plain_text):
            """如果传递的是路径，则读取文本"""
            with open(plain_text, 'rb') as text_file:
                plain_text = text_file.read()
        msg_text_plain = MIMEText(plain_text, 'plain', 'utf8')
        self.message.attach(msg_text_plain)
    
    def html_text_attach(self,html_text):
        """不需要做替换掉 html构造"""
        html_msg = MIMEText(html_text, 'html', 'utf-8')
        self.message.attach(html_msg)

    def add_image(self,image_path, cid):
        # 指定图片为当前目录
        with open(image_path, 'rb') as image_file:
            msg_image = MIMEImage(image_file.read())

        # 定义图片id，在html文本中引用
        msg_image.add_header('Content-ID', cid)
        self.message.attach(msg_image)
    def image_attach(self,image_file_path, imgid, filename=None):
        if filename is None:
            """如果不重命名文件，则默认使用源文件名"""
            filename = image_file_path
        try:
            with open(image_file_path, 'rb') as image_file:
                image_content = image_file.read()
        except Exception as ei:
            print('未找到图片文件', ei)
        image = MIMEImage(image_content)
        image.add_header('Content-ID', imgid)   # image1是照片别名，可以在HTML代码中引用
        image['Content-Disposition'] = f'attachment; filename={filename}'
        self.message.attach(image)
    
    def send_annex_file(self,annex_file_path, annex_filename=None):
        """传入附加文件路径和文件名(重命名附件，可以省略，默认为源文件名)"""
        if annex_filename is None:
            annex_filename = annex_file_path
        try:
            with open(annex_file_path, 'rb') as annex_file:
                send_file = annex_file.read()
        except Exception as es:
            print('未找到附件', es)

        text_appendix = MIMEText(send_file, 'base64', 'utf-8')
        text_appendix["Content-Type"] = 'application/octet-stream'
        # 以下附件可以重命名成：核心数据.xlsx
        # text_appendix["Content-Disposition"] = 'attachment; filename="核心数据.xlsx"'
        # 另一种附件重命名实现方式
        text_appendix.add_header('Content-Disposition', 'attachment', filename=annex_filename)
        self.message.attach(text_appendix)
    def initMsg(self,subject:str):
        self.message = MIMEMultipart('mixed')
        self.message['Subject'] = Header(subject, 'utf-8')           # 通过Header对象编码的文本，包含utf-8编码信息和Base64编码信息
        self.message['From'] = self.from_addr           # 括号里的对应发件人邮箱昵称（随便起）、发件人邮箱账号
    def send(self,to_addr:list):
        self.message['To'] = Header(';'.join(to_addr), 'utf-8') 
        self.server.sendmail(self.from_addr, to_addr, self.message.as_string())

    def quit(self):
        self.server.quit()

#main函数
if __name__ == '__main__':
    eu=EmailUtil('smtp.qq.com', 587, '757078144@qq.com', 'guyixnfhryhlbahj')
    eu.initMsg('发送附件和图片')
    eu.msg_text_attach('测试发送内容')
    eu.add_image('Q:\\SZHBWeChatRobot\\files\\ComfyUI_01493_.png', '1')
    eu.send_annex_file('Q:\\SZHBWeChatRobot\\files\\XXXABC.doc')
    eu.send(['langlangyan@live.com'])
    eu.quit()



